import subprocess
import threading

class Camera:
    def __init__(self, order_id):
        self.order_id = order_id
        self.process_pid = None
        self.start_camera_thread = threading.Thread(target=self.start_camera_thread_func, args=(order_id,))

    # 开启摄像头并保存视频到指定文件
    def start_camera(self):
        self.start_camera_thread.start()

    # 关闭摄像头
    def stop_camera(self):

        if self.process_pid:
            
            subprocess.run(['kill', str(self.process_pid)])

    # 开启摄像头的线程函数
    def start_camera_thread_func(self, order_id):

        filename = "/media/{}.mp4".format(order_id)
        # 线程函数中可以使用传递的参数
        command = ['ffmpeg', '-f', 'v4l2', '-i', '/dev/video0', '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '30', '-r', '5', '-b:v', '20k', filename]
        process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        self.process_pid = process.pid

    